<?php
/**
 * delete action
 * Khi delete 1 order can phai delete het tat ca cac table lien quan nhu la: shop_order_detail,
 * shop_order_tracking, shop_assignmemt, shop_surve_result
 *
 */

class Shop_OrderController extends Zend_Controller_Action
{
    /* ========== Backend actions =========================================== */

    /**
     * List order
     * @return void
    **/
    public function listAction()
    {
        $request = $this->getRequest();

        /**
        * Get current user
        **/
        $user = Zend_Auth::getInstance()->getIdentity();
        $this->view->assign('user', $user);

        /**
         * Get connection to database
         **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Order model access to data
         **/
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
         * Assignment access to db
         */
        $assignmentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('assignment')->getAssignmentDao();
        $assignmentDao->setDbConnection($conn);

         /**
        * Core User model access to db
        */
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
         * Enterprise basic model access to db
         */
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Evaluation basic model access to data
         */
        $evaluationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getEvaluationDao();
        $evaluationDao->setDbConnection($conn);

        /**
        * Get enterprise account to check permission
        */
        $userAccount = $userAccountDao->getByUser($user->user_id);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage   = 20;
        $offset    = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();

        /**
         * Build product search expression
         **/
        $params = null;
        $exp = array();

        /**
        * Check permission all list assignment
        */
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if($userAccount){
                $enterprise_id = (null != $userAccount->enterprise_id)?$userAccount->enterprise_id:null;
                $exp['enterprise_id'] = $purifier->purify($enterprise_id);
            }else{
                die('Not found enterpise id');
            }
        }

        /**
         * Get all process of tracking
         * $arrStatusIdOfAssignment: Store all status of process tracking
         **/
        $a_process = $assignmentDao->getPByType(2);
        $arrStatusIdOfAssignment = array();
        foreach($a_process as $a_pro){
            $arrStatusIdOfAssignment[$a_pro->status_id] = $a_pro->status_id;
        }

        /**
         * Get status for filter selectbox
         * $arrSStatus: store status info
         **/
        $arrSStatus = array();
        if($arrStatusIdOfAssignment){
            foreach($arrStatusIdOfAssignment as $s_id){
                $ojStatus = $assignmentDao->getSSById($s_id);
                $arrSStatus[] = $ojStatus;
            }
        }
        $this->view->assign('arrSStatus', $arrSStatus);

        /**
        * Filter
        **/
        if($request->isPost()){
            $order_created_form_date = $request->getParam('order_created_form_date');
            $order_created_to_date   = $request->getParam('order_created_to_date');
            $order_tracking_status   = $request->getParam('order_tracking_status');
            $order_status            = $request->getParam('order_status');

            /**
            * Check condition filter
            **/
            if('all' != $order_tracking_status){
                $exp['order_tracking_status'] = $order_tracking_status;
                $f_process = $assignmentDao->getPBySId($order_tracking_status);
                if(count($f_process) > 0){
                    $str_cond = null;
                    $i = 0;
                    foreach($f_process as $p_row){
                        $cond = "o.`process_id` = {$p_row->process_id}";
                        $cond1 = " or o.`process_id` = {$p_row->process_id}";
                        $str_cond .= ($i==0)?$cond:$cond1;
                        $i++;
                    }
                    $exp['process_id'] = $str_cond;
                }
            }

            if($order_created_form_date){
                $order_created_form_date = date('Y-m-d',strtotime($this->convertDateFormat($order_created_form_date)));
                $exp['order_created_form_date'] = $order_created_form_date;
            }
            if($order_created_to_date){
                $order_created_to_date = date('Y-m-d',strtotime($this->convertDateFormat($order_created_to_date)));
                $exp['order_created_to_date'] = $order_created_to_date;
            }
            if('all' != $order_status){
                $exp['order_status'] = $order_status;
            }

            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
        }
        else {
            $params = $request->getParam('q');
            if (null != $params) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }

        $order = $orderDao->find($offset, $perPage, $exp);
        $numOrder = $orderDao->count($exp);

        /**
         * $arrCustomer: array object customer info
         * $arrStatus: array object status
         * $arrEName : array enterprise name of each user
        **/
        $arrCustomer = array();
        $arrStatus = array();
        $arrEName = array();
        $arrEvalOrders = array();
        foreach($order as $r_order){

            /**
            * Get customer info for order
            **/
            $objuser = $userDao->getById($r_order->customer_id);
            $arrCustomer[$r_order->order_id] = $objuser;
            if($objuser){
                $objEU = $userAccountDao->getByUser($objuser->user_id);
                if($objEU){
                    $enterprise = $enterpriseDao->getById($objEU->enterprise_id);
                    $arrEName[$r_order->order_id.'_'.$objuser->user_id] = $enterprise->company_name_en;
                }
            }

            /**
            * Get tracking status info
            **/
            if($r_order->process_id){
                $status = $assignmentDao->getPSById($r_order->process_id);
                $arrStatus[$r_order->order_id] = $status->code;
            }

            /**
             * Check seller or buyer no evaluated yet
            **/
            $eval_exp['order_id'] = $r_order->order_id;
            $eval_orders = $evaluationDao->getById($eval_exp);
            $arrEvalOrders[$r_order->order_id] = $eval_orders;
        }
        $this->view->assign('arrCustomer', $arrCustomer);
        $this->view->assign('arrStatus', $arrStatus);
        $this->view->assign('arrEName', $arrEName);
        $this->view->assign('arrEvalOrders', $arrEvalOrders);

        /** Paginator*/
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($order, $numOrder));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('exp', $exp);
        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('order', $order);
        $this->view->assign('numOrder', $numOrder);

        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path'        => $this->view->url(array(), 'order_order_list'),
            'itemLink' => (null == $params)
                            ? 'page-%d/'
                            : 'page-%d/?q=' . $params,
        ));

    }

    /**
    * View order and order detail
    * @return void
    **/
    public function viewAction(){

        $request = $this->getRequest();
        $order_id = $request->getParam('order_id');
        /**
        * Get current user
        **/
        $user = Zend_Auth::getInstance()->getIdentity();
        $this->view->assign('user', $user);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Order models access to data
         **/
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * Attribute model access to db
        */
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);

        /**
        * Value model access to db
        */
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);

        /**
         * Assignment access to db
         */
        $assignmentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('assignment')->getAssignmentDao();
        $assignmentDao->setDbConnection($conn);

        /**
         * Enterprise basic model access to db
         */
        $enterpriseDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getEnterpriseDao();
        $enterpriseDao->setDbConnection($conn);

        /**
         * Evaluation models access to data
        **/
        $evaluationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getEvaluationDao();
        $evaluationDao->setDbConnection($conn);


        /**
        * Get order info by order id
        **/
        $order = $orderDao->getOrderById($order_id);
        $this->view->assign('order',$order);

        /**
        * Get enterprise account to check permission
        */
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
         * Check user belong to enterprise
        **/
        $user_enterprise = null;
        if(isset($userAccount->enterprise_id)){
            $user_enterprise = $userAccount->enterprise_id;
        }
        $this->view->assign('user_enterprise', $user_enterprise);

        /**
        * Check permission to view order detail
        **/
        $isAllowed = true;
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if(isset($userAccount->enterprise_id) && isset($order->enterprise_id)){
                if($userAccount->enterprise_id != $order->enterprise_id){
                    $isAllowed = false;
                    $this->view->assign('isAllowed', $isAllowed);
                    return;
                }
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        /**
         * Get enterprise name for user of order
         * $e_name: Name of enterprise
         **/
        $e_name = null;
        if($order->user_id){
            $objEU = $userAccountDao->getByUser($order->user_id);
            if($objEU){
                $enterprise = $enterpriseDao->getById($objEU->enterprise_id);
                $e_name = $enterprise->company_name_vn;
            }
        }
        $this->view->assign('e_name', $e_name);

        /**
         * Get tracking status for order
         **/
        $t_status = $assignmentDao->getPSById($order->process_id);
        $this->view->assign('t_status', $t_status);

        /**
        * Get product info by current order
        **/
        $products = $orderDao->getProductById($order_id);
        $this->view->assign('products',$products);

        /**
        * Get attribute and value of product in order
        **/
        $arrAllAtVal = array();
        if($products){
            foreach($products as $product){
                $at_val_chian = $product->product_value_type_id_chain;
                if($at_val_chian){
                    $arrAtValId = Zend_Json::decode($at_val_chian);
                    $arrAtVal = array();
                    foreach($arrAtValId as $key=>$row){
                        $attriubte = $attributeDao->getAttributeById($key);
                        $value = $valueDao->getById($row);
                        $arrAtVal[] = array($attriubte->attribute_type_admin_name, $value->value_type_name);
                    }
                    $arrAllAtVal[$product->order_detail_id] = $arrAtVal;
                }
            }
        }
        $this->view->assign('arrAllAtVal',$arrAllAtVal);

        /**
         * Get evaluation info where order status is finished
        **/
        $order_status = $t_status->code;
        if($order_status == 'finished'){
            /**
             * Order evaluation
            **/
            $order_exp['order_id'] = $order_id;
            $orderEval = $evaluationDao->getById($order_exp);
            $this->view->assign('orderEval', $orderEval);            
        }

        if($request->isPost()){
            $order_detail_id = $request->getPost('order_detail_id');
            $order_detail_exchange_return_cost = $request->getPost('order_detail_exchange_return_cost');
            $orderDetail = array(
                'order_detail_exchange_return_cost' => $order_detail_exchange_return_cost
            );
            $orderDao->updateOrderDetailCost($orderDetail, $order_detail_id);
            $this->_redirect($this->view->serverUrl().$this->view->url(array('order_id' => $order_id), 'order_order_view'));
        }
    }

    /**
     * View and update date tracking of order
     * @return void
    **/
    public function trackingAction(){
        $request = $this->getRequest();
        $order_id = $request->getParam('order_id');

        /**
        * Get current user
        **/
        $user = Zend_Auth::getInstance()->getIdentity();
        $this->view->assign('user', $user);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Order models access to data
        **/
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        /**
         * Assignment access to db
         */
        $assignmentDao = Tomato_Model_Dao_Factory::getInstance()->setModule('assignment')->getAssignmentDao();
        $assignmentDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        /**
        * User model access to db
        */
        $userDao = Tomato_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
        $userDao->setDbConnection($conn);

        /**
         * Get order info
        **/
        $order = $orderDao->getOrderById($order_id);
        $this->view->assign('order',$order);

        /**
        * Get enterprise by current user
        */
        $userAccount = $userAccountDao->getByUser($user->user_id);

        /**
        * Check permission all list assignment
        */
        $isAllowed = true;
        if(!Core_Services_RuleChecker::isAllowed('all-list')){
            if(isset($userAccount->enterprise_id) && isset($order->enterprise_id)){
                if($userAccount->enterprise_id != $order->enterprise_id){
                    $isAllowed = false;
                    $this->view->assign('isAllowed', $isAllowed);
                    return;
                }
            }
        }
        $this->view->assign('isAllowed', $isAllowed);

        /**
         * Get status for assignment
        **/
        $status = null;
        $objstatus = null;
        if($order->process_id){
            $objstatus = $assignmentDao->getPSById($order->process_id);
            if($objstatus){
                $status =$objstatus->code;
            }
        }        
        $this->view->assign('status', $status);

        /**
         * Get follow process for assignment
        **/
        $arrProcess = array();
        if($objstatus){
            $arrProcess = explode(',',substr(substr($objstatus->follow_process_id_chain,1),0,-1));
        }
        $this->view->assign('arrProcess', $arrProcess);

        /**
         * Get follow step for assignment
         * $arrSteps: store follow step
         * $strRoleId String performer_role_id_chain to check permission
        **/
        $arrSteps = array();
        $strRoleId = null;
        if($objstatus){
            $arrFollowSteps = explode(',',substr(substr($objstatus->follow_step_id_chain,1),0,-1));

            foreach($arrFollowSteps as $row){
                $step = $assignmentDao->getSSById($row);
                if($step){
                    $arrSteps[] = $step;

                    /**
                    * Buil string
                    **/
                    $strRoleId .= $step->performer_role_id_chain;
                }
            }

        }
        $this->view->assign('arrSteps', $arrSteps);
        $this->view->assign('strRoleId', $strRoleId);

        $trackings = $orderDao->getTracking($order_id);
        $this->view->assign('trackings',$trackings);

        /**
         * Get status by tracking
        **/
        $arrStatus = array();
        foreach($trackings as $tracking){
            $status = $assignmentDao->getPSById($tracking->process_id);
            $arrStatus[$tracking->order_tracking_id] = $status->code;
        }
        $this->view->assign('arrStatus', $arrStatus);

        if($request->isPost()){

            /**
            * Check for exception not permission
            **/
            if(!strstr($strRoleId, ','.$user->role_id.',')){
                return;
            }

            $process_id = $request->getPost('process_id');
            $order_tracking_remark = $request->getPost('order_tracking_remark');
            $order_tracking_cost = $request->getPost('order_tracking_cost');
            $order_tracking_date = $request->getPost('order_tracking_date');

            if(!$process_id){
                $this->_helper->getHelper('FlashMessenger')->addMessage(
                    $this->view->translator('tracking_not_found_next_process')
                );
                $this->_redirect($this->view->serverUrl().$this->view->url(array('order_id' => $order_id), 'order_order_tracking'));
            }

            $order = array(
                'process_id' => $process_id,
            );
            $orderDao->updateTracking($order, $order_id);

            $orderTracking= array(
                'order_id'              => $order_id,
                'process_id'            => $process_id,
                'order_tracking_date'   => date('Y-m-d', strtotime($this->convertDateFormat($order_tracking_date))),
                'order_tracking_remark' => $order_tracking_remark,
                'order_tracking_cost'   => $order_tracking_cost
            );
            $orderDao->addTracking($orderTracking);
            $this->_helper->getHelper('FlashMessenger')->addMessage(
                    $this->view->translator('tracking_save_success')
                );
            $this->_redirect($this->view->serverUrl().$this->view->url(array('order_id' => $order_id), 'order_order_tracking'));
        }
    }

    public function evaluationAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Evaluation models access to data
        **/
        $evaluationDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getEvaluationDao();
        $evaluationDao->setDbConnection($conn);

        /**
        * Enterprise User model access to db
        */
        $userAccountDao = Tomato_Model_Dao_Factory::getInstance()->setModule('enterprise')->getUserDao();
        $userAccountDao->setDbConnection($conn);

        if($request->isPost()){
            $order_id                   = $request->getPost('order_id');
            $seller_enterprise_id       = $request->getPost('enterprise_id');
            $seller_user_id             = $request->getPost('seller_id');
            $seller_to_buyer_evaluation = $request->getPost('point');
            $seller_to_buyer_feedback   = $request->getPost('evaluation');
            $customer_id                = $request->getPost('customer_id');

            $evaluations = new Shop_Models_Evaluation(array(
                'order_id'                   => $order_id,
                'seller_user_id'             => $seller_user_id,
                'seller_enterprise_id'       => $seller_enterprise_id,
                'seller_to_buyer_feedback'   => $seller_to_buyer_feedback,
                'seller_to_buyer_evaluation' => $seller_to_buyer_evaluation,
            ));
            if($request->getPost('update')){
                if($evaluationDao->update($evaluations, false)){
                    /**
                    * Check customer belong enterprise
                    */
                    $userAccount = $userAccountDao->getByUser($customer_id);
                    if($userAccount){
                        /**
                        * Update evaluation and counter for enterprise
                        **/
                        $evaluationEnt = array(
                            'enterprise_id'    => $userAccount->enterprise_id,
                            'evaluation_point' => $seller_to_buyer_evaluation
                        );
                        $evaluationDao->updateEnt($evaluationEnt);
                    }else{
                        /**
                        * Update evaluation and counter for customer
                        **/
                        $evaluationCus = array(
                            'customer_id'      => $customer_id,
                            'evaluation_point' => $seller_to_buyer_evaluation
                        );
                        $evaluationDao->updateCus($evaluationCus);
                    }

                    $this->_helper->getHelper('FlashMessenger')->addMessage(
                        $this->view->translator('order_evaluation_save_success')
                    );
                }else{
                    $this->_helper->getHelper('FlashMessenger')->addMessage(
                        $this->view->translator('order_evaluation_save_no_success')
                    );
                }
            }
            else{
                if($evaluationDao->add($evaluations)){
                    /**
                    * Check customer belong enterprise
                    */
                    $userAccount = $userAccountDao->getByUser($customer_id);
                    if($userAccount){
                        /**
                        * Update evaluation and counter for enterprise
                        **/
                        $evaluationEnt = array(
                            'enterprise_id'    => $userAccount->enterprise_id,
                            'evaluation_point' => $seller_to_buyer_evaluation
                        );
                        $evaluationDao->updateEnt($evaluationEnt);
                    }else{
                        /**
                        * Update evaluation and counter for customer
                        **/
                        $evaluationCus = array(
                            'customer_id'      => $customer_id,
                            'evaluation_point' => $seller_to_buyer_evaluation
                        );
                        $evaluationDao->updateCus($evaluationCus);
                    }

                    $this->_helper->getHelper('FlashMessenger')->addMessage(
                        $this->view->translator('order_evaluation_save_success')
                    );
                }else{
                    $this->_helper->getHelper('FlashMessenger')->addMessage(
                        $this->view->translator('order_evaluation_save_no_success')
                    );
                }
            }
            $this->_redirect($this->view->serverUrl().$this->view->url(array('order_id' => $order_id), 'order_order_view'));
        }
    }

    /*================ Not use functions======================*/
    public function editAction(){
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        $order_id = $this->getRequest()->getParam('order_id');
        $order = $orderDao->getOrderById($order_id);
        $this->view->assign('order',$order);
        if($order->order_tracking_status != 'open'){
            $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'order_order_list'));
        }

        $user = Zend_Auth::getInstance()->getIdentity();
        //get role
        $role = $orderDao->getRoleById($user->role_id);
        $this->view->assign('role',$role);
        /*//get customer
        $customer = $orderDao->getCustomerByUserId($user->user_id);
        $this->view->assign('customer',$customer);*/
        //check permission
        if($role->name == 'customer'){
            if($order->customer_id != $user->user_id){
                $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'order_order_list'));
            }
        }
        if($role->name == 'employee'){
            $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'order_order_list'));
        }

        $products = $orderDao->getProductById($order_id);
        $this->view->assign('products',$products);


        $arrAttribute = array();
        $arrAttributeValue = array();
        foreach ($products as $row){
            $arrAttribute1 = array();
            $arrAttributeValue1 = array();
            $productsAttribute = $orderDao->getAttributeTypeIdByProductId($row->product_id);
            //$arrAttributeValue = array();
            foreach ($productsAttribute as $row1){
                $attribute = $orderDao->getAttributeType($row1->attribute_type_id);
                $arrAttribute1[] = $attribute;

                $strAttribute = $row1->value_type_id_chain;
                $arrValue = explode(',', $strAttribute);
                unset($arrValue[0]);
                unset($arrValue[count($arrValue)]);
                $arrValues = array();
                foreach ($arrValue as $row2){
                    $value = $orderDao->getValue($row2);
                    $arrValues[] = $value;
                }
                $arrAttributeValue1[$row1->attribute_type_id] = $arrValues;
            }

            $arrAttribute[$row->product_id] = $arrAttribute1;
            $arrAttributeValue[$row->product_id] = $arrAttributeValue1;
        }
        $this->view->assign('arrAttributeValue',$arrAttributeValue);
        $this->view->assign('arrAttribute',$arrAttribute);
        $request = $this->getRequest();

        if ($order->order_modify_amount == 0 || $order->order_modify_amount == '')
        {
            $currAmount = $order->order_total_amount;
        }else{
            $currAmount = $order->order_modify_amount;
        }
        $old_order_total_shipping_cost = $order->order_total_shipping_cost;

        if($request->isPost()){
            $order_detail_id = $request->getPost('order_detail_id');
            $value_type_id = $request->getPost('value_type_id');
            $order_detail_quantity = $request->getPost('order_detail_quantity');
            $old_product_amount = $request->getPost('old_product_amount');
            $old_product_shipping_price = $request->getPost('old_product_shipping_price');
            $product_price = $request->getPost('product_price');
            $product_shipping_price = $request->getPost('product_shipping_price');
            $order_detail_exchange_return_cost = $request->getPost('order_detail_exchange_return_cost');
            $order_modify_amount_currency = $order->order_total_amount_currency;

            $strValueTypeId = ',';
            foreach ($value_type_id as $row){
                $strValueTypeId .= $row.',';
            }

            $orderDetail = array(
                'product_value_type_id_chain' => $strValueTypeId,
                'order_detail_quantity' => $order_detail_quantity
            );
            if($order_detail_quantity == 0){
                $orderDao->deleteOrderDetail($order_detail_id);
            }else{
                $orderDao->updateOrderDetail($orderDetail, $order_detail_id);
            }
            $new_product_shipping_price = $product_shipping_price*$order_detail_quantity-$old_product_shipping_price;
            $order_modify_amount = $product_price*$order_detail_quantity-$old_product_amount+$currAmount+$new_product_shipping_price;
            $order_total_shipping_cost = $product_shipping_price*$order_detail_quantity-$old_product_shipping_price+$old_order_total_shipping_cost;
            $order = array(
                'order_modified_date' => date('Y-m-d H:i:s'),
                'order_total_amount' => $order->order_total_amount,
                'order_modify_amount' => $order_modify_amount,
                'order_total_shipping_cost' => $order_total_shipping_cost,
                'order_modify_amount_currency'          => $order_modify_amount_currency,
                'order_edited'          => 1
            );
            $orderDao->update($order, $order_id);
            $this->_redirect($this->view->serverUrl().$this->view->url(array('order_id' => $order_id), 'order_order_edit'));
        }
    }

    public function trackinghistoryAction(){
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        $order_id = $this->getRequest()->getParam('order_id');
        $this->view->assign("order_id", $order_id);
        $orderTracking = $orderDao->getTracking($order_id);
        $this->view->assign('orderTracking',$orderTracking);
    }

    public function duplicateAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $result  = 0;
        $request = $this->getRequest();
        if($request->isPost()){
            $order_id = $request->getPost('order_id');

            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
            $orderDao->setDbConnection($conn);

            $order_id = $this->getRequest()->getParam('order_id');
            $order = $orderDao->getOrderById($order_id);

            $order_status = 'valid';
            $order_edited = 0;
            $order_created_date = date('Y-m-d H:i:s');
            $customer_id = $order->customer_id;
            $order_tracking_status = 'open';
            if($order->order_modify_amount > 0){
                $order_total_amount = $order->order_modify_amount;
                $order_total_amount_currency = $order->order_modify_amount_currency;
            }else{
                $order_total_amount = $order->order_total_amount;
                $order_total_amount_currency = $order->order_total_amount_currency;
            }
            $order_total_shipping_cost = $order->order_total_shipping_cost;
            $account_id = 1;
            //$invoicenumber = 'CCS'.date("ymdHis");
            $invoicenumber = 'CCS'.time();
            $shipping_id = $order->shipping_id;
            $data = new Tomato_Modules_Order_Models_Order(array(
                'order_status' => $order_status,
                'order_edited' => $order_edited,
                'order_created_date' => $order_created_date,
                'customer_id' => $customer_id,
                'order_tracking_status'           => $order_tracking_status,
                'order_total_amount'           => $order_total_amount,
                'order_total_amount_currency'           => $order_total_amount_currency,
                'order_total_shipping_cost' => $order_total_shipping_cost,
                'order_invoice' => $invoicenumber,
                'shipping_id' => $shipping_id,
                'account_id'           => $account_id
            ));
            $id = $orderDao->add($data);
            if($id){
                $orderDetails = $orderDao->getProductById($order_id);
                $id_detail = null;
                foreach($orderDetails as $row){
                    $order_id = $id;
                    $product_id = $row->product_id;
                    $order_detail_product_price = $row->order_detail_product_price;
                    $order_detail_product_price_currency = $row->order_detail_product_price_currency;
                    $order_detail_quantity = $row->order_detail_quantity;
                    $product_value_type_id_chain = $row->product_value_type_id_chain;
                    $order_detail_commission = $row->order_detail_commission;
                    if($row->order_detail_parent_id > 0 ){
                        $order_detail_parent_id = $id_detail;
                    }else{
                        $order_detail_parent_id = null;
                    }
                    $dataDetail = array(
                        'order_id' => $order_id,
                        'product_id' => $product_id,
                        'order_detail_product_price' => $order_detail_product_price,
                        'order_detail_product_price_currency' => $order_detail_product_price_currency,
                        'order_detail_quantity' => $order_detail_quantity,
                        'product_value_type_id_chain' => $product_value_type_id_chain,
                        'order_detail_parent_id' => $order_detail_parent_id,
                        'order_detail_commission' => $order_detail_commission
                    );

                    $idDetail = $orderDao->addDetail($dataDetail);
                    if($row->order_detail_parent_id <= 0 ){
                        $id_detail = $idDetail;
                    }
                    $result = $id;
                }
            }
        }
        $this->getResponse()->setBody($result);
    }

    public function editduplicateAction(){
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        $order_id = $this->getRequest()->getParam('order_id');
        $order = $orderDao->getOrderById($order_id);
        $this->view->assign('order',$order);

        $user = Zend_Auth::getInstance()->getIdentity();
        //get role
        $role = $orderDao->getRoleById($user->role_id);
        $this->view->assign('role',$role);
        /*//get customer
        $customer = $orderDao->getCustomerByUserId($user->user_id);
        $this->view->assign('customer',$customer);*/
        //check permission
        if($role->name == 'customer'){
            if($order->customer_id != $user->user_id){
                $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'order_order_list'));
            }
        }
        if($role->name == 'employee'){
            $this->_redirect($this->view->serverUrl().$this->view->url(array(), 'order_order_list'));
        }

        $products = $orderDao->getProductById($order_id);
        $this->view->assign('products',$products);


        $arrAttribute = array();
        $arrAttributeValue = array();
        foreach ($products as $row){
            $arrAttribute1 = array();
            $arrAttributeValue1 = array();
            $productsAttribute = $orderDao->getAttributeTypeIdByProductId($row->product_id);
            //$arrAttributeValue = array();
            foreach ($productsAttribute as $row1){
                $attribute = $orderDao->getAttributeType($row1->attribute_type_id);
                $arrAttribute1[] = $attribute;

                $strAttribute = $row1->value_type_id_chain;
                $arrValue = explode(',', $strAttribute);
                unset($arrValue[0]);
                unset($arrValue[count($arrValue)]);
                $arrValues = array();
                foreach ($arrValue as $row2){
                    $value = $orderDao->getValue($row2);
                    $arrValues[] = $value;
                }
                $arrAttributeValue1[$row1->attribute_type_id] = $arrValues;
            }

            $arrAttribute[$row->product_id] = $arrAttribute1;
            $arrAttributeValue[$row->product_id] = $arrAttributeValue1;
        }
        $this->view->assign('arrAttributeValue',$arrAttributeValue);
        $this->view->assign('arrAttribute',$arrAttribute);
        $request = $this->getRequest();

        if ($order->order_modify_amount == 0 || $order->order_modify_amount == '')
        {
            $currAmount = $order->order_total_amount;
        }else{
            $currAmount = $order->order_modify_amount;
        }
        $old_order_total_shipping_cost = $order->order_total_shipping_cost;

        if($request->isPost()){
            $order_detail_id = $request->getPost('order_detail_id');
            $value_type_id = $request->getPost('value_type_id');
            $order_detail_quantity = $request->getPost('order_detail_quantity');
            $old_product_amount = $request->getPost('old_product_amount');
            $product_price = $request->getPost('product_price');
            $old_product_shipping_price = $request->getPost('old_product_shipping_price');
            $product_shipping_price = $request->getPost('product_shipping_price');

            $order_modify_amount_currency = $order->order_total_amount_currency;

            $strValueTypeId = ',';
            foreach ($value_type_id as $row){
                $strValueTypeId .= $row.',';
            }

            $orderDetail = array(
                'product_value_type_id_chain' => $strValueTypeId,
                'order_detail_quantity' => $order_detail_quantity,
            );
            if($order_detail_quantity == 0){
                $orderDao->deleteOrderDetail($order_detail_id);
            }else{
                $orderDao->updateOrderDetail($orderDetail, $order_detail_id);
            }
            $order_modify_amount = $product_price*$order_detail_quantity-$old_product_amount+$currAmount;
            $order_total_shipping_cost = $product_shipping_price*$order_detail_quantity-$old_product_shipping_price+$old_order_total_shipping_cost;
            $order = array(
                'order_modified_date' => date('Y-m-d H:i:s'),
                'order_total_amount' => $order_modify_amount,
                'order_modify_amount' => null,
                'order_total_shipping_cost' => $order_total_shipping_cost,
                'order_modify_amount_currency'          => $order_modify_amount_currency,
                'order_edited'          => 0
            );
            $orderDao->update($order, $order_id);
            $this->_redirect($this->view->serverUrl().$this->view->url(array('order_id' => $order_id), 'order_order_edit_duplicate'));
        }
    }

    public function deleteAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);

        $request = $this->getRequest();
        $result  = 'RESULT_ERROR';
        if ($request->isPost()) {
            $order_id = $request->getPost('id');
            $orderDao->delete($order_id);
            $result = 'RESULT_OK';
        }
        $this->getResponse()->setBody($result);
    }

    public function trackingMailAction(){
        $orderId = $this->getRequest()->getParam('order_id');
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $productDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getProductDao();
        $productDao->setDbConnection($conn);
        $orderDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getOrderDao();
        $orderDao->setDbConnection($conn);
        $order = $orderDao->getOrderInfoById($orderId);
        //get email format
        $shopmailDao = Tomato_Model_Dao_Factory::getInstance()->setModule('Shopmail')->getShopmailDao();
        $shopmailDao->setDbConnection($conn);
        $mail_id = 3;
        $mail = $shopmailDao->getMailById($mail_id);

        //form send order mail
        $order_name = $order->full_name;
        $order_invoiceNumber = $order->order_invoice;
        $order_shippingAddress = "<div>First name: {$order->shipping_first_name}</div>";
        $order_shippingAddress .= "<div>Last name: {$order->shipping_last_name}</div>";
        $order_shippingAddress .= "<div>Address: {$order->shipping_address}</div>";
        $order_shippingAddress .= "<div>City: {$order->shipping_city}</div>";
        $order_shippingAddress .= "<div>State: {$order->shipping_state}</div>";
        $order_shippingAddress .= "<div>Zip/Postal code: {$order->shipping_zipcode}</div>";
        $order_shippingAddress .= "<div>Telephone: {$order->shipping_telephone}</div>";
        $order_shippingAddress .= "<div>Email address: {$order->shipping_email}</div>";

        $orderDetail = $orderDao->getProductById($orderId);
        /*$arrSubAdditionalPrice = array();
        foreach($orderDetail as $row){
            $arrAttribute = explode(',',substr($row->product_value_type_id_chain,1,strlen($row->product_value_type_id_chain)-2));
            $key = $row->order_detail_id;
            $$key = 0;
            if($arrAttribute){
                $subAdditionalPrice1 = 0;
                foreach($arrAttribute as $row1){
                    $value = $orderDao->getValue($row1);
                    $subAdditionalPrice1 += @$value->value_type_price*@$row->order_detail_quantity;
                }
                if($row->order_detail_parent_id){
                    $order_detail_parent_id = $row->order_detail_parent_id;
                    $$order_detail_parent_id += $subAdditionalPrice1;
                    $arrSubAdditionalPrice[$order_detail_parent_id ] = $$order_detail_parent_id ;
                }
            }
        }*/
        $order_detail = '<table width="100%" border="0" cellpadding="5" cellspacing="" style="padding: 10px;">
                            <tr height="25" style="padding: 10px;">
                                <td width="50" align="left" valign="bottom" class="c_title"><strong>No.</strong></td>
                                <td width="250" align="left" valign="bottom" class="c_title"><strong>Item</strong></td>
                                <td width="250" align="left" valign="bottom" class="c_title"><strong>Color</strong></td>
                                <td width="100" align="left" valign="bottom" class="c_title"><strong>Price</strong></td>
                                <td width="50" align="left" valign="bottom" class="c_title"><strong>Qty.</strong></td>
                                <td width="100" align="left" valign="bottom" class="c_title"><strong>Subtotal</strong></td>
                            </tr>';

        $i = 1; $inProductionPrice = 0;
        $giftcardDao = Tomato_Model_Dao_Factory::getInstance()->setModule('Giftcard')->getGiftcardDao();
        $giftcardDao->setDbConnection($conn);
        $giftcard = $giftcardDao->getCategoryByName('Giftcards');
        $coupon = $giftcardDao->getCategoryByName('Coupons');
        foreach($orderDetail as $row){
        $product = $productDao->getProductById($row->product_id);
        if($product->category_id != ",{$giftcard->category_id}," && $product->category_id != ",{$coupon->category_id},"){
            $color = '';
            $attributeTypes = $orderDao->getAttributeTypeIdByProductId($row->product_id);
            foreach($attributeTypes as $row1){
                $attributeType = $orderDao->getAttributeType($row1->attribute_type_id);
                if($attributeType->attribute_type_admin_name == 'Fabric'){
                    $value_type_id_chain = $row1->value_type_id_chain;
                    $arrValueType = explode(',',substr($value_type_id_chain,1,strlen($value_type_id_chain)-2));
                    foreach($arrValueType as $row2){
                        if(strstr($row->product_value_type_id_chain, ",{$row2},")){
                            $value = $orderDao->getValue($row2);
                            $color = $attributeType->attribute_type_admin_name.': '.$value->value_type_name;
                        }
                    }
                }
            }
            $order_detail .='<tr style="border-bottom: 1px solid #F3F3F5;">
                                <td>';
                                if($row->order_detail_parent_id == null){
                                $order_detail .= $i++;
                                }
            $order_detail .=    '</td><td>';
                                if($row->order_detail_parent_id != null){
                                $order_detail .= '---'.$product->product_content_name;
                                }else{
                                $order_detail .= $product->product_content_name;
                                }
            $order_detail .=    '</td>
                                <td>'.$color.'</td><td>';
                                if($row->order_detail_parent_id == null){
                                $order_detail .= '$';
                                $order_detail .= $row->order_detail_product_price/$row->order_detail_quantity;
                                }
            $order_detail .=    '</td><td>';
                                if($row->order_detail_parent_id != null || $product->product_bundle == 1){
                                }else{
                                $order_detail .= $row->order_detail_quantity;
                                }
            $order_detail .=    '</td><td>';
                                if($row->order_detail_parent_id == null){
                                $order_detail .= '$';
                                $order_detail .= $row->order_detail_product_price;
                                }
            $order_detail .=    '</td>
                            </tr>';
            }else{
                $inProductionPrice += $row->order_detail_product_price;
            }
        }
        $order_detail .= '</table>';
        //echo $order_detail;die;
        $estimatedTotal = $order->order_modify_amount?$order->order_modify_amount:$order->order_total_amount;
        $shippingPrice = $order->order_total_shipping_cost;
        $total = $estimatedTotal-$shippingPrice-$inProductionPrice;
        $inProductionPrice = $inProductionPrice*-1;
        $order_summary = "<div>Subtotal: $".$total."</div>";
        $order_summary .= "<div>Shipping & Handling: $".$shippingPrice."</div>";
        $order_summary .= "<div>Giftcard / Coupon: $".$inProductionPrice."</div>";
        $order_summary .= "<div>ESTIMATED TOTAL: $".$estimatedTotal."</div>";
        //format mail content
        $mailContent = $mail->mail_content;
        $mailContent = str_replace('order_name',$order_name,$mailContent);
        $mailContent = str_replace('order_invoiceNumber',$order_invoiceNumber,$mailContent);
        $mailContent = str_replace('order_shippingAddress',$order_shippingAddress,$mailContent);
        $mailContent = str_replace('order_detail',$order_detail,$mailContent);
        $mailContent = str_replace('order_summary',$order_summary ,$mailContent);

        $from = "info@capitolcustomsuits.com";
        $to = $order->email;
        $bcc = "viet@startech.vn";
        $content = $mailContent;
        $subject = "Capitol custom suits order, invoice number ".$order_invoiceNumber;
        $transport = Tomato_Modules_Mail_Services_Mailer::getMailTransport();
        $mail = new Zend_Mail();
        $mail->setFrom($from)
            ->addTo($to)
            ->addBcc($bcc)
            ->setSubject($subject)
            ->setBodyHtml($content)
            ->send($transport);
        //end form send order mail
        echo $mailContent;die;
    }

    public function printAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->viewAction();
    }
    /*================ End not use functoin=================*/

    /**
     * Format date to strtotime function use
     * @return string
     */
    public function convertDateFormat($time){
        $a = explode("/", $time);
        $ts = $a[2].'/'.$a[1].'/'.$a[0];
        return $ts;
    }
}